package com.athuahua.spzx.listener;

import cn.hutool.core.date.DateTime;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.athuahua.spzx.entity.Category;
import com.athuahua.spzx.mapper.CategoryMapper;
import com.athuahua.spzx.vo.product.CategoryExcelVo;
import org.springframework.beans.BeanUtils;

import java.util.List;

/**
 * @Author: huahua
 * @Date: 2024/7/29 0029
 * @Time: 14:28
 * @Description:
 */
//监听器 监听器不能让spring管理
public class ExcelListener<T> implements ReadListener<T> {

    private final CategoryMapper categoryMapper;

    //缓存数据
    private static final int BATCH_SIZE = 1000;
    private List<T> cacheDataList = ListUtils.newArrayListWithExpectedSize(BATCH_SIZE);

    //构造传递mapper
    public ExcelListener(CategoryMapper mapper) {
        this.categoryMapper = mapper;
    }



    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        //每行数据对象T 放到list集合中
        cacheDataList.add(t);
        //达到批量处理的阈值 批量处理
        if (cacheDataList.size() >= BATCH_SIZE) {
            saveData();
            //清理list集合
            cacheDataList = ListUtils.newArrayListWithExpectedSize(BATCH_SIZE);
        }
    }



    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //把剩下的数据批量保存到数据库中
        saveData();
    }


    private void saveData() {
        for (CategoryExcelVo categoryExcelVo : (List<CategoryExcelVo>) cacheDataList) {
            Category category = new Category();
            BeanUtils.copyProperties(categoryExcelVo, category);
            category.setUpdateTime(new DateTime());
            category.setCreateTime(new DateTime());
            category.setIsDeleted(0);
            categoryMapper.insert(category);
        }

    }
}
